const Record = require('../model/record.model')
const {pgBuildParam} = require("../tool/toolPage");
const {Op} = require("sequelize");

//数据库操作
class RecordService {
    //用户注册
    async saveData({id, title, context, person, state}) {
        //插入数据
        let res;
        if (!id) {
            res = await Record.create({
                title, context, person, state
            }).dataValues
        } else {
            const whereOpt = {id}
            const newObj = {id}
            title && Object.assign(newObj, {title})
            context && Object.assign(newObj, {context})
            person && Object.assign(newObj, {person})
            state && Object.assign(newObj, {state})
            let up = await Record.update(newObj, {where: whereOpt})
            if (up[0] > 0) {
                res = newObj;
            }
        }
        return res;
    }

    async pageRecord({pageNow = 1, size = 10}) {
        //插入数据
        const whereOpt = {id: {[Op.gt]: 0}}
        const {count, rows} = await Record.findAndCountAll({
            // attributes: ['id', 'username', 'password', 'phone', 'is_admin'],
            where: whereOpt,
            offset: (pageNow - 1) * size,
            limit: size
        })
        return pgBuildParam({pageNow, size}, count, rows)
    }

    //搜索用户名
    async getRecord({id}) {
        const whereOpt = {}
        id && Object.assign(whereOpt, {id})
        const res = await Record.findOne({
            // attributes: ['id', 'username', 'password', 'phone', 'is_admin'],
            where: whereOpt
        })

        return res ? res.dataValues : null
    }

    //修改用户信息
    async updateRecord({id, title, context, person, state}) {
        const whereOpt = {id}
        const newObj = {}
        title && Object.assign(newObj, {title})
        context && Object.assign(newObj, {context})
        person && Object.assign(newObj, {person})
        state && Object.assign(newObj, {state})
        const res = await Record.update(newObj, {where: whereOpt})
        return res[0] > 0
    }
}

module.exports = new RecordService()